package com.itianyu.blog.web.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.ClassEditor;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.itianyu.blog.dao.beans.Page;
import com.itianyu.blog.dao.beans.User;
import com.itianyu.blog.dao.interfaces.PageInterface;
import com.itianyu.blog.dao.interfaces.UserInterface;
import com.itianyu.blog.validation.PageValidator;

/**
 * 文章控制层
 * @author wumgji
 */
@Controller
@RequestMapping("/page")
public class PageController {

	@Autowired
	private PageInterface pageInterface;

	@Autowired
	private UserInterface userInterface;

	@Autowired
	private PageValidator pageValidator; // 文章表单验证

	// 绑定表单数据，转化Spring不能直接处理的数据
	@InitBinder
	protected void initBinder(HttpServletRequest request, ServletRequestDataBinder dataBinder) throws Exception {
		DateFormat df = new SimpleDateFormat("MM/dd/yyyy k:mm");
		df.setLenient(false);
		dataBinder.registerCustomEditor(Date.class, "creationDate", new CustomDateEditor(df, false));

		dataBinder.registerCustomEditor(User.class, "user", new ClassEditor() {
			public void setAsText(String text) {
				setValue(userInterface.findUser(text));
			}
		});

	}

	// 显示文章列表
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public ModelAndView listPages() throws Exception {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		User user = ((User) authentication.getPrincipal());
		return new ModelAndView("pagelist", new ModelMap().addAttribute("pages", pageInterface.findPageEntities(user)));
	}

	// 根据文章ID编辑文章信息
	@RequestMapping(value = "/{pageId}/edit", method = RequestMethod.GET)
	public ModelAndView editPage(@PathVariable("pageId") int pageId) {
		if (pageId == 0) {// 如果pageId为0，新增文章
			Page page = pageInterface.createPage();

			page.setCreationDate(new Date());

			page.setUser((User) ((SecurityContext) SecurityContextHolder.getContext()).getAuthentication().getPrincipal());

			// 0代表文章不显示在菜单
			page.setMenuOrder(0);

			return new ModelAndView("pageform", new ModelMap().addAttribute("page", page));
		} else {
			Page page = pageInterface.findPage(pageId);
			return new ModelAndView("pageform", new ModelMap().addAttribute("page", page));
		}
	}

	// 保存文章信息（pageId参数作用仅是保持url一致性）
	@RequestMapping(value = "/{pageId}/save", method = RequestMethod.POST)
	public ModelAndView savePage(@PathVariable("pageId") int pageId, @ModelAttribute("page") Page page, BindingResult result) {
		page.setModificationDate(new Date());
		pageValidator.validate(page, result);

		if (result.hasErrors()) {
			// 加载验证错误信息，然后返回表单
			return new ModelAndView("pageform");
		} else {
			page = pageInterface.savePage(page);
			// return new ModelAndView ("redirect:/app/page/list");
			return new ModelAndView("redirect:/app/page/" + page.getPageId());// redirect避免重复提交
		}
	}

	// 根据文章ID删除文章信息
	@RequestMapping(value = "/{pageId}/delete", method = RequestMethod.GET)
	public ModelAndView deletePage(@PathVariable("pageId") int pageId) {
		pageInterface.deletePage(pageId);
		// return new ModelAndView ("redirect:/app/page/" + page.getPageId());
		return new ModelAndView("redirect:/app/page/list");
	}

	// 根据文章ID查看文章信息
	@RequestMapping(value = "/{pageId}", method = RequestMethod.GET)
	public ModelAndView viewPage(@PathVariable("pageId") int pageId) {
		if (pageInterface.findPage(pageId) != null) {
			return new ModelAndView("pageview", new ModelMap().addAttribute("page", pageInterface.findPage(pageId)));
		}

		return new ModelAndView("pageview", new ModelMap().addAttribute("page", null));
	}

	// 查询文章列表的标题
	@RequestMapping(value = "/count", method = RequestMethod.GET)
	@ResponseBody
	public List<Object[]> pageCount() throws Exception {
		return pageInterface.findPageTitles();
	}

}
